/**
 * Copyright (c) 2012 Tomi Paananen.
 *
 * Part of Quick Gestures user interface.
 */

import QtQuick 1.1
import com.nokia.symbian 1.1
import QuickGestures 1.0

Page {
    id: gestureListPage

    property StorageThread storageThread: engine.storageThread
    property GestureModel gestureModel: engine.model
    property string currentFilePath: ""
    property string latestFilePath: "" // Kept in memory even when the list is cleared

    Connections {
        target: storageThread

        onStateChanged: {
            console.debug("Storage thread state changed to " + state);

            if (state == StorageThread.Idle) {
                progressLabel.hideDelayed(2000);
            }
            else {
                if (state == StorageThread.Loading) {
                    progressLabel.text = "Loading...";
                }
                else {
                    progressLabel.text = "Saving...";
                }

                progressLabel.shown = true;
            }
        }
        onProgress: progressLabel.value = percentsComplete / 100;
    }

    // If no gestures exist (loaded nor created), show "No gestures" text and
    // provide buttons for quick access for loading and creating gestures.
    EmptyPageInfo {
        id: emptyPageInfo
        text: "No gestures"
        visible: !gestureModel.count
    }
    Column {
        anchors {
            top: emptyPageInfo.bottom
            horizontalCenter: parent.horizontalCenter
            margins: 20
        }

        visible: emptyPageInfo.visible
        spacing: 10
        z: 1

        Button {
            width: 150
            text: "Load"
            onClicked: viewMenu.loadClicked();
        }
        Button {
            width: 150
            text: "Create"
            onClicked: pageStack.push(editorPage, { gestureId: -1 });
        }
    }

    // For showing the progress of loading and saving.
    ProgressLabel {
        id: progressLabel
        width: parent.width - 10

        anchors {
            top: parent.top
            left: parent.left
            right: parent.right
            margins: 5
        }

        z: 1
        text: "Idle"
        determinate: true
        shown: false
    }

    // The view header shows the file name of the current gesture set.
    Component {
        id: viewHeader

        ViewHeader {
            width: parent ? parent.width : 360;
            height: 55
            visible: !emptyPageInfo.visible

            text: {
                var content = currentFilePath.length ?
                            helper.extractFilenameFromPath(currentFilePath)
                          : "Untitled";

                if (helper.modifiedGesturesCount) {
                    content += "*";
                }

                return content;
            }
        }
    }

    // Grid view containing the gestures.
    GridView {
        id: gridView
        property GestureListItem selectedGestureListItem

        anchors {
            fill: parent
            leftMargin: 5
        }

        cellWidth: 117
        cellHeight: 117

        model: gestureModel

        header: viewHeader

        delegate: GestureListItem {
            id: gestureListItem
            width: 110
            height: width

            onSelected: {
                gridView.selectedGestureListItem = gestureListItem;
                gestureListItemCSMenu.open();
            }

            Connections {
                target: helper

                onModified: {
                    if (id == gestureListItem.gestureId) {
                        console.debug("GestureListPage.qml: gestureListItem::onModified:", id);
                        gestureListItem.isModified = true;
                        gestureListItem.rescale();
                        gestureListItem.play();
                    }
                }
                onModifiedGesturesCountChanged: {
                    if (!helper.modifiedGesturesCount) {
                        gestureListItem.isModified = false;
                    }
                }
            }

            // Make sure that the animations are stopped when the view is
            // moving.
            Connections {
                target: gridView
                onMovementStarted: gestureListItem.state = "Stopped";
                onMovementEnded: gestureListItem.state = "Playing";
            }
            Component.onCompleted: {
                if (gridView.moving || gridView.flicking) {
                    gestureListItem.state = "Stopped";
                }
            }
        }
    }
    ScrollDecorator {
        flickableItem: gridView
    }

    // Pages.
    Component {
        id: fileManagerPage

        FileManagerPage {
            currentFilePath: gestureListPage.latestFilePath

            onLoad: {
                helper.clearModifiedGestures();

                if (gestureModel.count) {
                    gestureModel.clear();
                }

                storageThread.loadByUrl(filePath);
                gestureListPage.currentFilePath = filePath;
                gestureListPage.latestFilePath =
                        helper.removeFileFromPath(filePath);
            }
            onSaveTo: {
                helper.saveGestures(filePath, root.engine);
                helper.clearModifiedGestures();
                gestureListPage.currentFilePath = filePath;
                gestureListPage.latestFilePath =
                        helper.removeFileFromPath(filePath);
            }
        }
    }
    Component {
        id: editorPage
        EditorPage { model: gestureModel }
    }
    Component {
        id: recognitionPage
        RecognitionPage { engine: root.engine }
    }
    Component {
        id: aboutPage
        AboutPage {}
    }

    // Loader for loading the pages.
    Loader {
        id: loader
        onLoaded: pageStack.push(item);
    }

    // The menu for selected gesture list items.
    Menu {
        id: gestureListItemCSMenu

        content: MenuLayout {
            MenuItem {
                text: "Edit"
                platformSubItemIndicator: true

                onClicked: {
                    if (gridView.selectedGestureListItem) {
                        pageStack.push(editorPage,
                            { gestureId: gridView.selectedGestureListItem.gestureId });
                    }
                    else {
                        console.debug("GestureListPage.qml: Error: No gesture "
                                      + "list item selected!");
                    }
                }
            }
            MenuItem {
                text: "Remove"

                onClicked: {
                    if (!gridView.selectedGestureListItem) {
                        console.debug("GestureListPage.qml: Error: No gesture "
                                      + "list item selected!");
                        return;
                    }

                    var id = gridView.selectedGestureListItem.gestureId;

                    if (gestureModel.removeGesture(id)) {
                        console.debug("GestureListPage.qml: Removed a gesture "
                                      + "with ID", id);
                        helper.setModified(id);
                    }
                    else {
                        console.debug("GestureListPage.qml: Failed to delete "
                                      + "a gesture with ID", id);
                    }

                    gridView.selectedGestureListItem = null;
                }
            }
        }

        onStatusChanged: {
            if (status == DialogStatus.Closed) {
                if (gridView.selectedGestureListItem) {
                    gridView.selectedGestureListItem.isSelected = false;
                    gridView.selectedGestureListItem = null;
                }
            }
        }
    }

    // The main view menu.
    MainViewMenu {
        id: viewMenu

        clearEnabled: (gestureModel.count > 0);
        saveEnabled: helper.modifiedGesturesCount

        onClearClicked: {
            engine.clearModel();
            helper.clearModifiedGestures();
            currentFilePath = "";
        }
        onLoadClicked: pageStack.push(fileManagerPage, { saveMode: false });

        onSaveClicked: {
            if (!currentFilePath.length) {
                // Open the file manager page.
                pageStack.push(fileManagerPage, { saveMode: true });
            }
            else {
                storageThread.saveByUrl(currentFilePath);
                helper.clearModifiedGestures();
            }
        }

        onSaveAsClicked: pageStack.push(fileManagerPage, { saveMode: true });
        onAboutClicked: pageStack.push(aboutPage);
    }

    tools: ToolBarLayout {
        ToolButton {
            iconSource: "toolbar-back"
            onClicked: Qt.quit();
        }
        ToolButton {
            iconSource: "qrc:/edit-icon.png"
            onClicked: pageStack.push(editorPage, { gestureId: -1 });
        }
        ToolButton {
            iconSource: "qrc:/recognize-icon.png"
            onClicked: pageStack.push(recognitionPage);
        }
        ToolButton {
            iconSource: "toolbar-menu"
            onClicked: viewMenu.open();
        }
    }
}
